import { useRef, useState } from 'react';
import { useDrag, useDrop } from 'react-dnd';
import { useFlowStore } from '../../stores/flowStore';
import { NodeStatus } from '../../common/types';
import './NodeStyles.css';

interface ConnectionPointProps {
  type: 'input' | 'output';
  position: 'top' | 'right' | 'bottom' | 'left';
  onConnectStart?: () => void;
  onConnectEnd?: () => void;
}

const ConnectionPoint = ({ 
  type, 
  position,
  onConnectStart,
  onConnectEnd 
}: ConnectionPointProps) => {
  const [isHovered, setIsHovered] = useState(false);

  return (
    <div 
      className={`connection-point ${type} ${position} ${isHovered ? 'active' : ''}`}
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      onMouseDown={onConnectStart}
      onMouseUp={onConnectEnd}
    >
      <div className="connection-handle" />
    </div>
  );
};

export const FunctionNode = ({ node }: { node: FlowNode }) => {
  const nodeRef = useRef<HTMLDivElement>(null);
  const [isConnecting, setIsConnecting] = useState(false);
  
  // Store actions
  const updateNodePosition = useFlowStore((state) => state.updateNodePosition);
  const setSelectedNode = useFlowStore((state) => state.setSelectedNode);
  const removeNode = useFlowStore((state) => state.removeNode);
  const addConnection = useFlowStore((state) => state.addConnection);

  // Drag handler
  const [, drag] = useDrag(() => ({
    type: 'NODE',
    item: { nodeId: node.id },
    collect: (monitor) => ({
      isDragging: monitor.isDragging()
    })
  }));

  // Drop handler
  const [, drop] = useDrop(() => ({
    accept: 'NODE',
    drop: (draggedItem: { nodeId: string }) => {
      if (draggedItem.nodeId !== node.id) {
        // 处理节点连接逻辑
      }
    }
  }));

  // 开始创建连接
  const handleConnectionStart = (position: string) => {
    setIsConnecting(true);
    // 可以存储当前连接起点信息
  };

  // 完成连接
  const handleConnectionEnd = (position: string) => {
    if (isConnecting) {
      setIsConnecting(false);
      // 这里可以添加实际的连接创建逻辑
    }
  };

  // 合并drag和drop的ref
  drag(drop(nodeRef));

  // 状态颜色映射
  const statusColors: Record<NodeStatus, string> = {
    idle: '#409EFF',
    success: '#67C23A',
    error: '#F56C6C'
  };

  return (
    <div
      ref={nodeRef}
      className={`function-node ${node.status}`}
      style={{
        left: `${node.position.x}px`,
        top: `${node.position.y}px`,
        borderColor: statusColors[node.status],
        boxShadow: isConnecting ? '0 0 0 2px #409EFF' : 'none'
      }}
      onDoubleClick={(e) => {
        e.stopPropagation();
        setSelectedNode(node.id);
      }}
    >
      {/* 连接点（四个方向） */}
      <ConnectionPoint 
        type="output" 
        position="top" 
        onConnectStart={() => handleConnectionStart('top')}
        onConnectEnd={() => handleConnectionEnd('top')}
      />
      <ConnectionPoint 
        type="output" 
        position="right"
        onConnectStart={() => handleConnectionStart('right')}
        onConnectEnd={() => handleConnectionEnd('right')}
      />
      <ConnectionPoint 
        type="output" 
        position="bottom"
        onConnectStart={() => handleConnectionStart('bottom')}
        onConnectEnd={() => handleConnectionEnd('bottom')}
      />
      <ConnectionPoint 
        type="output" 
        position="left"
        onConnectStart={() => handleConnectionStart('left')}
        onConnectEnd={() => handleConnectionEnd('left')}
      />

      {/* 节点内容 */}
      <div className="node-header">
        <span className="node-title">{node.functionId}</span>
        <button 
          className="node-delete-btn"
          onClick={(e) => {
            e.stopPropagation();
            removeNode(node.id);
          }}
        >
          ×
        </button>
      </div>
      
      <div className="node-body">
        {Object.entries(node.parameters).map(([key, value]) => (
          <div key={key} className="param-row">
            <span className="param-name">{key}:</span>
            <span className="param-value">{String(value)}</span>
          </div>
        ))}
      </div>

      {node.status !== 'idle' && (
        <div className="node-status-indicator" style={{ 
          backgroundColor: statusColors[node.status] 
        }} />
      )}
    </div>
  );
};